<template>
  <div class="umsUser-add-update-component">
    <el-dialog
      v-if="modelValue.visible"
      v-model="modelValue.visible"
      :title="
        !modelValue.form.id
          ? `新增${modelValue.title}`
          : `修改${modelValue.title}`
      "
      width="550px"
    >
      <div style="padding-right: 50px; padding-top: 10px">
        <el-form
          :model="modelValue.form"
          :rules="modelValue.rules"
          ref="addEditRef"
          :label-width="40"
        >
          <el-form-item prop="file">
            <div>门店excel</div>
            <el-upload
              style="width: 100%"
              ref="uploadRef"
              class="upload-demo"
              :before-upload="canUpload"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :auto-upload="false"
              drag
              action="/storeservice/storeGroup/batchLoad"
              :on-change="handleFileChange"
              :file-list="modelValue.form.fileList"
              :headers="uploadHeaders"
            >
              <div class="update-demo-content">
                <div>
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                </div>
                <div class="el-upload__text">
                  将文件拖到此处, 或<em>点击上传</em>
                </div>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!modelValue.disabled">
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button :loading="loading" type="primary" @click="ensure">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElUpload, ElIcon, FormInstance } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import { batchAddStore } from "@/api/tms-store.api";

const props = defineProps(["modelValue"]);

const uploadRef = ref();
const addEditRef = ref<FormInstance>();
const canUpload = async (rawFile) => {
  let name = rawFile.name;
  let index = name.lastIndexOf(".");
  let exet = name.substring(index + 1);

  if (!(exet === "bin")) {
    ElMessage({
      message: "只接受固件升级文件",
      type: "error",
    });
    return false;
  }
  return true;
};

const handleFileChange = (file) => {
  let fileList = props.modelValue.form.fileList;
  if (!fileList) {
    props.modelValue.form.fileList = [];
  }
  props.modelValue.form.fileList.push(file);
  console.log("当前文件:", file.raw); // 关键：获取原始文件对象
};

const uploadHeaders = {
  token: localStorage.getItem("TOKEN"),
};

const uploadError = (err, file, fileList) => {
  ElMessage({
    message: err.msg || err,
    type: "error",
  });
};

const uploadSuccess = (response, file, fileList) => {
  ElMessage({
    message: "图片上传成功",
    type: "success",
  });
  return;
};

/***
 * 确认弹框
 */
const ensure = () => {
  updateVersionWithFile();
};

const loading = ref(false);
const updateVersionWithFile = () => {
  const formData1 = new FormData();
  let fileList = props.modelValue.form.fileList || [];
  formData1.append("file", fileList[0].raw);

  if (!addEditRef.value) return;
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      batchAddStore(formData1)
        .then((res: any) => {
          loading.value = false;
          cancel();
          ElMessage({
            message: props.modelValue.title + "新增成功",
            type: "success",
          });
          if (props.modelValue.refreshDataList) {
            props.modelValue.refreshDataList();
          }
        })
        .catch((err: any) => {
          loading.value = false;
          ElMessage({
            message: err.msg || err,
            type: "error",
          });
        });
    }
  });
};

/***
 * 取消弹框
 */
const cancel = () => {
  props.modelValue.visible = false;
};
</script>

<style lang="scss" scoped>
.update-demo-content {
  display: flex;
  flex-direction: column;
}
</style>
